package pl.koziolekweb.prusakolep.dao;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import pl.koziolekweb.prusakolep.App;
import pl.koziolekweb.prusakolep.model.Bug;

/**
 * 
 * @author bartlomiejk
 * 
 * 
 *         $Id: BugDAO.java 119 2009-02-17 22:36:34Z bjkuczynski $
 */
public class BugDAO {

	private static Long sequence;

	static {
		synchronized (BugDAO.class) {
			File seq = new File("./seq");
			if (!seq.exists()) {
				try {
					seq.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
				sequence = -1L;
			} else {
				FileInputStream fis = null;
				try {
					fis = new FileInputStream(seq);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
					System.exit(1);
				}
				
				DataInputStream in = new DataInputStream(fis);
				BufferedReader br = new BufferedReader(
						new InputStreamReader(in));
				String seqS="";
				try {
					seqS = br.readLine();
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
					System.exit(1);
				}
				Pattern pattern = Pattern.compile("^[0-9]*$");
				Matcher matcher = pattern.matcher(seqS);
				if (matcher.matches()) {
					sequence = Long.parseLong(seqS);
				}
			}
		}
	}

	public static synchronized Long sequence() {
		sequence = sequence + 1L;
		return sequence;
	}

	public void persist(Bug bug) throws FileNotFoundException, IOException {
		File dbb = new File(App.PATH + "/" + bug.getId());
		dbb.createNewFile();
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
				dbb));
		oos.writeObject(bug);
		persistSequence(); // after persist object sequence is been persist.
	}

	public Bug read(Long id) throws FileNotFoundException, IOException,
			ClassNotFoundException {
		Bug bug = null;
		File dbb = new File(App.PATH + "/" + id);
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream(dbb));
		bug = (Bug) ois.readObject();
		return bug;
	}

	private void persistSequence() {
		File seq = new File("./seq");
		FileOutputStream fos;
		try {
			fos = new FileOutputStream(seq);
			fos.write(sequence.toString().getBytes());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Throwable e) {
			e.printStackTrace();
		}

	}

}
